package com.glory.brepda.activity.mfg;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.glory.brepda.R;
import com.glory.brepda.base.BaseActivity;
import com.glory.brepda.base.MyApp;
import com.glory.brepda.entity.MLotListEntity;
import com.glory.brepda.entity.MaterielListEntity;
import com.glory.brepda.entity.response.BaseResponseBean;
import com.glory.brepda.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.journeyapps.barcodescanner.BarcodeEncoder;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralFragmentDialog;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DialogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StaticMembers;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MaterielUpActivity extends BaseActivity {


    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;
    @BindView(R.id.etEqpWork)
    FreeUI_ClearEditText etEqpWork;
    @BindView(R.id.etEqpWorkPosition)
    FreeUI_ClearEditText etEqpWorkPosition;
    @BindView(R.id.etMaterielLot)
    FreeUI_ClearEditText etMaterielLot;
    @BindView(R.id.etLot)
    FreeUI_ClearEditText etLot;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.ivPositionArrow)
    ImageView ivPositionArrow;
    @BindView(R.id.image)
    ImageView image;
    @BindView(R.id.flPositionList)
    FrameLayout flPositionList;
    @BindView(R.id.llProductmainQTY)
    LinearLayout llProductmainQTY;
    @BindView(R.id.llConsumemainQTY)
    LinearLayout llConsumemainQTY;
    @BindView(R.id.etProductmainQTY)
    FreeUI_ClearEditText etProductmainQTY;
    @BindView(R.id.etConsumemainQTY)
    FreeUI_ClearEditText etConsumemainQTY;
    private List<String> mMaterielList;
    private FreeUI_GeneralPop mMaterielPop;
    private String state = "";
    private String POSITIONNAME = "";


    @Override
    protected int getLayoutResId() {
        return R.layout.activity_materiel_up;
    }

    @Override
    protected void initView() {
        String title = getIntent().getStringExtra(FreeApi_StaticMembers.SHOW_PLUGIN_KEY);
        tvTitle.setText(title);
        setMainLayout(llMain);
        mMaterielList = new ArrayList<>();
        String eqpid = getIntent().getExtras().getString("EQPID");
        String position = getIntent().getExtras().getString("POSITION");
        if (eqpid != null) {
            etEqpWork.setText(eqpid);
            requestMaterielList(eqpid);
        }

        if (position != null) {
            etEqpWorkPosition.setText(position);
        }

        initEdit(etEqpWork, s -> requestMaterielList(s));
        initEdit(etMaterielLot,s->{
            image.setImageBitmap(encodeAs(s));
        });
    }

    private void requestMaterielList(String eqpid) {
        FreeUI_EntityCallBack<BaseResponseBean<MaterielListEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<MaterielListEntity>>
                (new TypeToken<BaseResponseBean<MaterielListEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<MaterielListEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    mMaterielList.clear();
                    List<MaterielListEntity.Materiel> positionsetlines = response.body().getResponse().getBody().getPOSITIONSET().getPOSITIONSETLINES();
                    for (MaterielListEntity.Materiel positionsetline : positionsetlines) {
                        mMaterielList.add(positionsetline.getPOSITIONNAME() + "/" + positionsetline.getPOSITIONDESC());
                        etEqpWorkPosition.setText(mMaterielList.get(0).split("/")[1]);
                        POSITIONNAME = mMaterielList.get(0).split("/")[0];
                    }
                    etLot.setText(response.body().getResponse().getBody().getLOTID());
                    state = response.body().getResponse().getBody().getSTATE();
                    if (state.equals("TRUE")){
                        llProductmainQTY.setVisibility(View.VISIBLE);
                        llConsumemainQTY.setVisibility(View.VISIBLE);
                    }else {
                        llProductmainQTY.setVisibility(View.GONE);
                        llConsumemainQTY.setVisibility(View.GONE);
                    }
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<MaterielListEntity>> response) {
                super.onError(response);
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("EQUIPMENTID",eqpid);
        map.addProperty("ACTIONTYPE","EQPPOSITIONSET");
        NetUtils.requestPostNet("IF.MLOTKITTING", "POSITIONMANAGE", MaterielUpActivity.this, map, callBack);
    }

    @Override
    protected void initData() {

    }

    @OnClick({R.id.tvBaseSubmit, R.id.ivPositionArrow})
    public void onViewClicked(View v) {
        if (v.getId() == R.id.tvBaseSubmit) {
//            if (actionControl("Submit14")) {
//                return;
//            }

            if (getText(etEqpWork).equals("") || getText(etEqpWorkPosition).equals("") || getText(etMaterielLot).equals("")) {
                showToast("填写未完成，请填写相关数据", false);
                return;
            }

            showSubmitDialog(new onSubmitListener() {
                @Override
                public void setOnSubmitListener() {
                    FreeUI_EntityCallBack<BaseResponseBean<MaterielListEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<MaterielListEntity>>
                            (new TypeToken<BaseResponseBean<MaterielListEntity>>() {
                            }.getType(), getSupportFragmentManager(), this) {

                        @Override
                        public void onSuccess(Response<BaseResponseBean<MaterielListEntity>> response) {
                            super.onSuccess(response);
                            if (response.body().isSuccess(getApplicationContext(), false, getSupportFragmentManager())) {
                                if (response.body().getResponse().getBody().getSHOW_MSG().contains("已被暂停")){
                                    FreeUI_GeneralFragmentDialog tipDialog = FreeApi_DialogUtils.getConfirmDialog(MyApp.app,
                                            "确定", response.body().getResponse().getBody().getSHOW_MSG(), () -> {
                                    });
                                    tipDialog.show(getSupportFragmentManager(),"DIALOG");
                                }else {
                                    etMaterielLot.setText("");
                                    etMaterielLot.requestFocus();
                                    showToast("物料上机成功", true);
                                }
                            }
                        }

                        @Override
                        public void onError(Response<BaseResponseBean<MaterielListEntity>> response) {
                            super.onError(response);
                        }
                    };
                    JsonObject map = new JsonObject();
                    map.addProperty("ACTIONTYPE", "ATTACH");
                    MLotListEntity mLotListEntity = new MLotListEntity(getText(etMaterielLot), POSITIONNAME);
                    List<MLotListEntity> list = new ArrayList<>();
                    list.add(mLotListEntity);
                    map.add("MLOTLIST", new JsonParser().parse(new Gson().toJson(list)).getAsJsonArray());
                    map.addProperty("EQUIPMENTID", getText(etEqpWork));
                    map.addProperty("POSITIONNAME", POSITIONNAME);
                    map.addProperty("LOTID", getText(etLot));
                    map.addProperty("STATE", state);
                    map.addProperty("PRODUCTMAINQTY", getText(etProductmainQTY));
                    map.addProperty("CONSUMEMAINQTY", getText(etConsumemainQTY));
                    NetUtils.requestPostNet("IF.MLOTKITTING", "MLOTKITTING3", MaterielUpActivity.this, map, callBack);

                }
            });

        } else if (v.getId() == R.id.ivPositionArrow) {
            if (mMaterielList.size() <= 0){
                showToast("未获取到物料上料位列表",false);
            }

            mMaterielPop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flPositionList.getWidth(), mMaterielList, ivPositionArrow, (codeS, i) -> {
                etEqpWorkPosition.setText(codeS.split("/")[1]);
                POSITIONNAME = codeS.split("/")[0];
            });
            FreeApi_PopUtils.setArrowShow(ivPositionArrow);
            mMaterielPop.showAsDropDown(flPositionList, 0, 0);
        }
    }
    public Bitmap encodeAs(String str) {
        Bitmap bitmap = null;
        BitMatrix result = null;
        MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
        try {
            result = multiFormatWriter.encode(str, BarcodeFormat.QR_CODE, 200, 200);
            // 使用 ZXing Android Embedded 要写的代码
            BarcodeEncoder barcodeEncoder = new BarcodeEncoder();
            bitmap = barcodeEncoder.createBitmap(result);
        } catch (WriterException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException iae) {
            return null;
        }
        return bitmap;
    }

}
